package com.fary.web.accept;

import com.fary.core.SpringException;
import com.fary.http.HttpHeaders;
import com.fary.http.MediaType;
import com.fary.util.CollectionUtils;
import com.fary.web.context.request.NativeWebRequest;

import java.util.Arrays;
import java.util.List;

public class HeaderContentNegotiationStrategy implements ContentNegotiationStrategy {

    @Override
    public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws SpringException {

        String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT);
        if (headerValueArray == null) {
            return MEDIA_TYPE_ALL_LIST;
        }

        List<String> headerValues = Arrays.asList(headerValueArray);
        try {
            List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
            MediaType.sortBySpecificityAndQuality(mediaTypes);
            return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST;
        } catch (SpringException ex) {
            throw new SpringException("Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
        }
    }

}